/**
 * libssl fuzzer for libfuzzer.
 *
 * Compile with:
 * $ ./make.sh libssl_fuzzer.cc -lssl -lcrypto
 */

#include <openssl/ssl.h>
#include <openssl/err.h>
#include <assert.h>
#include <stdint.h>
#include <stddef.h>

#define CERT "server.pem"
#define KEY "server.key"

SSL_CTX *Init()
{
        SSL_library_init();
        SSL_load_error_strings();
        ERR_load_BIO_strings();
        OpenSSL_add_all_algorithms();
        SSL_CTX *sctx;
        assert (sctx = SSL_CTX_new(TLSv1_method()));
        assert(SSL_CTX_use_certificate_file(sctx, CERT, SSL_FILETYPE_PEM));
        assert(SSL_CTX_use_PrivateKey_file(sctx, KEY, SSL_FILETYPE_PEM));
        return sctx;
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
{
        static SSL_CTX *sctx = Init();
        SSL *server = SSL_new(sctx);
        BIO *sinbio = BIO_new(BIO_s_mem());
        BIO *soutbio = BIO_new(BIO_s_mem());
        SSL_set_bio(server, sinbio, soutbio);
        SSL_set_accept_state(server);
        BIO_write(sinbio, Data, Size);
        SSL_do_handshake(server);
        SSL_free(server);
        return 0;
}
